//
//  HDImagesZoomView.m
//  HDecoration
//
//  Created by koki on 15-4-25.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDImagesZoomView.h"
#import "MSMarkBtnView.h"

#define MaxZoomScaleNum 2.5
#define MinZoomScaleNum 1.0


@interface HDImagesZoomView ()
{
    UITableView *m_TableView;
    //图片标题
    UILabel *titleLabel;
    //图百分比
    UILabel *progressLabel;
    //分区按钮
    MSMarkBtnView *markView;
}
@end

@implementation HDImagesZoomView
@synthesize index;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        [self _initView];
    }

    return self;
}

-(void)setDataArray:(NSArray *)dataArray
{
    _dataArray=dataArray;
    [m_TableView reloadData];
    if (dataArray.count)
    {
        MSImage* item=self.dataArray[0];
        titleLabel.text = item.title;
        progressLabel.text = item.info;
    }
    m_TableView.hidden=!dataArray.count;
}

-(void)setMarkArray:(NSArray *)markArray
{
    _markArray=markArray;
    markView.dataArray=markArray;
    markView.hidden=!markArray.count;
}

- (void)setImageIndex:(NSInteger)imageIndex {
    _imageIndex = imageIndex;
    index = imageIndex;
    if (!self.dataArray.count || index > self.dataArray.count-1) {
        return;
    }
    MSImage* item=self.dataArray[index];
    titleLabel.text = item.title;
    progressLabel.text = item.info;
    if (self.imageViewType == MSImageViewTypeComment) {
        markView.hidden = YES;
        progressLabel.text = [NSString stringWithFormat:@"%ld/%ld",imageIndex+1,self.dataArray.count];
    }
    if (self.markArray.count)
    {
        NSInteger m_index= [self.markArray indexOfObject:item.mark];
        markView.m_IndexPath=[NSIndexPath indexPathForItem:m_index inSection:0];
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:imageIndex inSection:0];
    [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
    
    [m_TableView reloadData];
}

-(void)reloadData
{
   [m_TableView reloadData];
}

- (void)_initView
{
    if (_isRotate) {
        m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
//        progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, self.height-100, 40, 40)];
//        progressLabel.transform = CGAffineTransformMakeRotation(M_PI / 2);
    }
    else{
        m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.height, self.frame.size.width) style:UITableViewStylePlain];
        m_TableView.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
        m_TableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
        
    }
    m_TableView.delegate = self;
    m_TableView.dataSource = self;
    m_TableView.showsVerticalScrollIndicator = NO;
    m_TableView.pagingEnabled = YES;
    m_TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    m_TableView.backgroundView = nil;
    m_TableView.backgroundColor = [UIColor blackColor];
    [self addSubview:m_TableView];
    
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,self.height-100, self.width-40-40, 40)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor colorWithWhite:0.85 alpha:1];
    titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:14];
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:titleLabel];
    
    progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width-60,self.height-100, 40, 40)];
    progressLabel.backgroundColor = [UIColor clearColor];
    progressLabel.textColor = [UIColor colorWithWhite:0.85 alpha:1];
    progressLabel.font = [UIFont fontWithName:@"STHeitiSC-Light" size:14];
    progressLabel.textAlignment = NSTextAlignmentRight;
    [self addSubview:progressLabel];
    
    markView=[[MSMarkBtnView alloc] initWithFrame:CGRectMake(0,self.height-50, self.width,30)];
    markView.delegate=self;
    [self insertSubview:markView aboveSubview:m_TableView];
    self.clipsToBounds=YES;
    self.backgroundColor=[UIColor blackColor];
}

-(void)markViewSelected:(NSString*)mark
{
    NSIndexPath* indexPath=[NSIndexPath indexPathForItem:0 inSection:0];
    for (int i=0;i<self.dataArray.count-1;i++)
    {
        MSImage* item =self.dataArray[i];
        if ([item.mark isEqualToString:mark])
        {
            index=i;
            self.imageIndex = index;
            indexPath=[NSIndexPath indexPathForItem:index inSection:0];
            [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
            MSImage* item=self.dataArray[index];
            titleLabel.text = item.title;
            progressLabel.text = item.info;
            return;
        }
    }
    [m_TableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *idty = @"imgshowCell";
    ZoomImgItem *cell = [tableView dequeueReusableCellWithIdentifier:idty];
    if (nil == cell)
    {
        cell = [[ZoomImgItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idty];
        cell.contentView.transform = CGAffineTransformMakeRotation(M_PI / 2);
    }
    cell.imgName = @"ic_no_img_detail";
    if (_isRotate) {
        cell.rect = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
    }
    else{
        cell.rect = self.bounds;
    }
    MSImage* picInfo=[self.dataArray objectAtIndex:indexPath.row];
    cell.imgName = picInfo.url;

    if(indexPath.row>=index && indexPath.row<=index+2)
    {
        if (indexPath.row<self.dataArray.count-1)
        {
            [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section]];
        }
    }
    else if(indexPath.row<index && indexPath.row>=index-2)
    {
        if (indexPath.row>0)
        {
            [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]];
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isRotate) {
        return self.frame.size.height;
    }else{
        return self.frame.size.width;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSIndexPath *indexPath =  [m_TableView indexPathForRowAtPoint:scrollView.contentOffset];
    index=indexPath.row;
    _imageIndex = index;
    if (!self.dataArray.count || index > self.dataArray.count-1) {
        return;
    }
    MSImage* item=self.dataArray[index];
    titleLabel.text = item.title;
    progressLabel.text = item.info;
    //评论图片类型
    if (self.imageViewType == MSImageViewTypeComment) {
        if (_isRotate) {
            progressLabel.text = [NSString stringWithFormat:@"%ld/%ld",labs((int)(scrollView.contentOffset.y/self.frame.size.height)+1),(unsigned long)self.dataArray.count];
        }else{
            progressLabel.text = [NSString stringWithFormat:@"%ld/%ld",labs((int)(scrollView.contentOffset.y/self.frame.size.width)+1),(unsigned long)self.dataArray.count];
        }
    }
    if (self.markArray.count)
    {
       NSInteger m_index= [self.markArray indexOfObject:item.mark];
       markView.m_IndexPath=[NSIndexPath indexPathForItem:m_index inSection:0];
    }
}

@end

@implementation ZoomImgItem

- (void)dealloc {
    self.imgName = nil;
    self.zoomImgView=nil;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [self _initView];
    }
    return self;
}

- (void)_initView
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor=[UIColor clearColor];
    self.zoomImgView = [[ZoomImgView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:self.zoomImgView];
    self.clipsToBounds=NO;
}

- (void)setImgName:(NSString *)imgName
{
    _imgName=[imgName copy];
    self.frame=self.rect;
    [self.zoomImgView  resetViewFrame:self.rect];
    self.zoomImgView.imageView.imgURLStr=imgName;
}

@end



@implementation ZoomImgView
@synthesize scrollView,imageView,containerView;

-(void)dealloc
{
    imageView=nil;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}

- (void)initView {
    self.clipsToBounds = YES;
    self.contentMode = UIViewContentModeScaleAspectFill;
    scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.bounces = NO;
    scrollView.backgroundColor=[UIColor clearColor];
    [self addSubview:scrollView];
    
    containerView.clipsToBounds=NO;
    containerView = [[UIView alloc] initWithFrame:self.bounds];
    [scrollView addSubview:containerView];
    
    imageView = [[DOImageView alloc] initWithFrame:self.bounds];
    imageView.contentMode=UIViewContentModeScaleAspectFit;
    imageView.userInteractionEnabled=YES;
    imageView.delegate=(id)self;
    imageView.needCache=YES;
    [containerView addSubview:imageView];
    
    //双击
    UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                       action:@selector(TapsAction:)];
    [doubleTapGesture setNumberOfTapsRequired:2];
    [scrollView addGestureRecognizer:doubleTapGesture];
    
    //单击
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(TapsAction:)];
    [tapGesture setNumberOfTapsRequired:1];
    [scrollView addGestureRecognizer:tapGesture];
    
    //双击失败之后执行单击
    [tapGesture requireGestureRecognizerToFail:doubleTapGesture];
    
    self.scrollView.maximumZoomScale = MaxZoomScaleNum;
    self.scrollView.minimumZoomScale = MinZoomScaleNum;
    self.scrollView.zoomScale = MinZoomScaleNum;
}

- (float)getImgWidthFactor
{
    return   self.bounds.size.width / self.imageView.image.size.width;
}

- (float)getImgHeightFactor
{
    return  self.bounds.size.height / self.imageView.image.size.height;
}

- (CGSize)newSizeByoriginalSize:(CGSize)oldSize maxSize:(CGSize)mSize
{
    if (oldSize.width <= 0 || oldSize.height <= 0)
    {
        return CGSizeZero;
    }
    
    CGSize newSize = CGSizeZero;
    if (oldSize.width > mSize.width || oldSize.height > mSize.height)
    {
        //按比例计算尺寸
        float bs = [self getImgWidthFactor];
        float newHeight = oldSize.height * bs;
        newSize = CGSizeMake(mSize.width, newHeight);
        
        if (newHeight > mSize.height)
        {
            bs = [self getImgHeightFactor];
            float newWidth = oldSize.width * bs;
            newSize = CGSizeMake(newWidth, mSize.height);
        }
    }
    else
    {
        newSize = oldSize;
    }
    return newSize;
}

- (void)doImageViewLoad:(DOImageView*)imgView img:(UIImage*)img
{
    CGSize showSize=[self newSizeByoriginalSize:img.size maxSize:self.bounds.size];
    self.imageView.frame = CGRectMake(0, 0, showSize.width, showSize.height);
    scrollView.zoomScale  = 1;
    scrollView.contentOffset = CGPointZero;
    containerView.bounds = imageView.bounds;
    scrollView.zoomScale  = scrollView.minimumZoomScale;
    [self scrollViewDidZoom:scrollView];
}

#pragma mark- 手势事件
//单击 / 双击 手势
- (void)TapsAction:(UITapGestureRecognizer *)tap
{
    NSInteger tapCount = tap.numberOfTapsRequired;
    if (2 == tapCount)
    {
        //双击
        if (self.scrollView.minimumZoomScale <= self.scrollView.zoomScale && self.scrollView.maximumZoomScale > self.scrollView.zoomScale)
        {
            [self.scrollView setZoomScale:self.scrollView.maximumZoomScale animated:YES];
        }
        else
        {
            [self.scrollView setZoomScale:self.scrollView.minimumZoomScale animated:YES];
        }
    }
}


- (void)resetViewFrame:(CGRect)newFrame
{
    self.rect=newFrame;
    self.frame = newFrame;
    scrollView.frame = self.bounds;
    containerView.frame = self.bounds;
    imageView.frame=self.bounds;
}

#pragma mark- Scrollview delegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return containerView;
}

- (void)scrollViewDidZoom:(UIScrollView *)m_scrollView
{
    CGFloat Ws = scrollView.frame.size.width - scrollView.contentInset.left - scrollView.contentInset.right;
    CGFloat Hs = scrollView.frame.size.height - scrollView.contentInset.top - scrollView.contentInset.bottom;
    CGFloat W = containerView.frame.size.width;
    CGFloat H = containerView.frame.size.height;
    CGRect rct = containerView.frame;
    rct.origin.x = MAX((Ws-W)*0.5, 0);
    rct.origin.y = MAX((Hs-H)*0.5, 0);
    containerView.frame = rct;
}


@end





